﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Web.Http;
using User.Api.Dto.BillOrder;
using User.Api.Helpers;
using System.Linq;
using System.Web.Http.Controllers;
using Common.Logging;
using OutDbContext;
using User.Api.BizExtensions;
using In.Api.Dto.HisWs;
using User.Api.HttpClients;
using System.Net.Http;
using Newtonsoft.Json;
using User.Api.Dto.Bill;

namespace User.Api.Controllers
{
    public class BillOrderController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(BillOrderController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有缴费订单，只显示取号成功的订单
        /// </summary>
        /// <param name="type">current - 15内订单 history - 历史订单</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderList")]
        public GetOrderListResponse GetOrderList(string type = "current")
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCard.FirstOrDefault(x => x.WxUserId == azUser.UserId && x.IsDefault == 1);
            if (card == null)
            {
                return new GetOrderListResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }
            List<BillOrder> orders;
            
            if (type == "current")
            {
                orders =
                    _ctx.BillOrder.Where(x => x.CardNo == card.CardNo).IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) <= 15)
                        .OrderByDescending(x => x.OrderDate).ThenByDescending(x => x.CreateTime).ToList();
            }
            else
            {
                orders =
                    _ctx.BillOrder.Where(x => x.CardNo == card.CardNo).IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                        .Where(x => SqlFunctions.DateDiff("day", x.CreateTime, DateTime.Today) > 15)
                        .OrderByDescending(x => x.OrderDate).ThenByDescending(x => x.CreateTime).ToList();
            }

            return new GetOrderListResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Orders = orders.Select(x => new GetOrderListResponse.Order
                {
                    OrderId = x.Id,
                    OrderNo = x.OrderNo,
                    CardNo = x.CardNo,
                    CardName = x.CardName,
                    ClinicNo=x.ClinicNo,
                    OrderDate = x.OrderDate,
                    OrderDept = x.OrderDept,
                    FetchTime = x.FetchTime.ToString(),
                    PrescMoney = x.PrescMoney.GetValueOrDefault().ToString("F2")
                }).ToList()

            };
        }

        /// <summary>
        /// 获取缴费订单详情
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetOrderDetail")]
        public GetOrderDetailResponse GetOrderDetail( int orderId)
        {
            var azUser = AzUser.GetInApi(Request);
            var order = _ctx.BillOrder.IsStatus(BillOrderExtensions.OrderStatus.缴费成功)
                .FirstOrDefault(x => x.WxUserId == azUser.UserId && x.Id == orderId);
            if (order == null)
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "1",
                    ResultMsg = "订单不存在"
                };
            }
            var request = new GetCompletedPayDetailInfoRequest();
            request.AdmInfo = order.ClinicNo;
            request.ReceiptId = order.RealRcptNo;

            GetCompletedPayDetailInfoResponse respons;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetCompletedPayDetailInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                respons = responseMsg.Content.ReadAsAsync<GetCompletedPayDetailInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取缴费订单详情出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetOrderDetailResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取缴费单详情超时"
                };
            }

            if(respons.ResultCode!="0")
            {
                return new GetOrderDetailResponse
                {
                    ResultCode = "3",
                    ResultMsg = respons.ResultDesc
                };
            }

            var Today = DateTime.Now.ToString("yyyy-MM-dd");
            var Remark = "0";
            if (Today == order.OrderDate)
            {
                Remark = "1";
            }

            var response = new GetOrderDetailResponse
            {
                ResultCode = "0",
                ResultMsg = Remark,//1 显示
                OrderId = orderId,
                FetchTime = order.FetchTime.ToString(),
                OrderNo = order.OrderNo,
                CardNo = order.CardNo,
                CardName = order.CardName,
                ClinicNo = order.ClinicNo,
                PrescMoney = order.PrescMoney.GetValueOrDefault().ToString("F2"),
                OrderDept = order.OrderDept,
                OrderDate = order.OrderDate,
                RealRcptNo = order.RealRcptNo,
                HasYiBao = order.YiBaoStatus == BillOrderExtensions.YiBaoStatus.使用了医保.ToInt32()
                    && !string.IsNullOrEmpty(order.YiBaoJydjh),
                Charges = order.YibaoMoney.GetValueOrDefault().ToString("F2"),
                Cost = order.PersonalMoney.GetValueOrDefault().ToString("F2")
            };

            response.Items = respons.OEOrdItemList.Select(x => new GetOrderDetailResponse.BillItem
            {
                Account = x.Qty,
                ItemPrice = x.ItemPrice.ToDecimalOrDefault().ToString("F2"),
                Money = x.Account.ToDecimalOrDefault().ToString("F2"),
                Name = x.NameDesc,
                //Type = x.Type,
                NameDesc = x.NameDesc,
                RecLoc = x.RecLoc,
                RecAddress=x.RecAddress,
                Unit = x.Unit

            }).ToList();

            response.DisWins = _ctx.BillOrderDisWin.Where(x => x.BillOrderId == orderId).ToList()
                .Select(x => new GetOrderDetailResponse.DisWinItem
                {
                    //RcptNo = x.RcptNo,
                    VisitNo = x.VisitNo,
                    DisWinAdd = x.DisWinAdd,
                    DisWin = x.DisWin
                }).ToList();

            return response;
        }
    }
}
